import dayjs from 'dayjs'
import { tooltipConfig } from './config'
import { FAULT_COLOR, NORMAL_COLOR, LINE_COLOR } from './costant'
import locationIcon from "@/assets/location-icon.png";
import locationIconRed from "@/assets/location-icon-red.png";

const getMockLineData = (startTime, endTime) => {
	const oneDay = 1000 * 60 * 60 * 24
	const result = []
	const dayNum = (endTime - startTime) / oneDay;
	let value = 0
	let max = Math.ceil(Math.random() * 15 + 15)
	for (let i = 0; i <= dayNum; i++) {
		if (max < 0) max = 0
		const date = startTime + oneDay * i
		result.push({
			date,
			value
		})
		value += max
		max -= 6
	}
	return result;
}
/**
 * 画虚线
 * @param {Number} height 虚线高度
 * @param {Array} point 虚线的开始坐标
 * @returns 
 */
const getDashedLine = (height, point, color) => {
	const result = [];
	let y1 = point[1];
	while (height > 10) {
		y1 += 10;
		const y2 = y1 + 10;
		height -= 10;
		result.push({
			type: "line",
			shape: {
				x1: point[0],
				y1: y1,
				x2: point[0],
				y2,
			},
			style: {
				stroke: color,
				lineWidth: 3,
			},
		});
		y1 += 10;
	}
	return result;
}
// 曲线分布图
export const getCurveSeries = (seriesData, axisIndex, color) => {
	return {
		name: 'legendNameCurve',
		type: "custom",
		clip: true,
		renderItem: function (params, api) {
			const startDate = api.value(0);
			const endDate = api.value(1);
			const pointDate = api.value(2);
			const polylineStyle = {
				stroke: color,
				fill: null,
				lineWidth: 3,
			};
			// 高亮样式
			const emphasisStyle = {
				style: {
					lineWidth: 3,
				},
			};
			const list = getMockLineData(startDate, endDate);
			const endValue = list.at(-1).value;
			const dashedStartPoint = api.coord([endDate, endValue]);
			const pointItem = list.find((x) => x.date === pointDate);
			const points = list.map((item) => api.coord([item.date, item.value]));
			const dashedHeight = api.size([endDate, endValue]);
			const result = {
				type: "group",
				silent: true,
				children: [
					// 曲线
					{
						type: "polyline", //折线
						shape: {
							points,
							smooth: 0.3,
						},
						style: polylineStyle,
						emphasis: emphasisStyle,
					},
					//虚线
					...getDashedLine(dashedHeight[1], dashedStartPoint, color),
				],
			};
			//拐点
			if (pointItem) {
				const pointPosition = api.coord([pointItem.date, pointItem.value]);
				result.children.push({
					type: "circle",
					shape: {
						cx: pointPosition[0],
						cy: pointPosition[1],
						r: 4,
					},
					style: {
						fill: color,
					},
				});
			}
			return result;
		},
		encode: {
			x: 0,
			y: 3,
		},
		tooltip: {
			show: false,
		},
		data: seriesData,
		xAxisIndex: axisIndex,
		yAxisIndex: axisIndex,
	}
}
// 自定义柱状图
export const getCustomBarSeries = (seriesData, axisIndex) => {
	return {
		name: "legendName",
		type: "custom",
		clip: true,
		renderItem: function (params, api) {
			const yValue = api.value(3);
			const polylineStyle = api.style({
				stroke: null,
			});
			const emphasisStyle = {
				style: {
					opacity: 0.6,
				},
			};
			const x1 = api.coord([api.value(0), 0]);
			const x2 = api.coord([api.value(0), yValue]);
			const x3 = api.coord([api.value(1), yValue]);
			const x4 = api.coord([api.value(1), 0]);

			return {
				type: "polyline", //折线
				z2: -1,
				shape: {
					points: [x1, x2, x3, x4],
					smooth: 0,
				},
				style: polylineStyle,
				emphasis: emphasisStyle,
			};
		},
		encode: {
			x: 0,
			y: 3,
		},
		tooltip: {
			...tooltipConfig,
			formatter: function (params) {
				const { value } = params.data;
				return `<div class='echarts-tooltip-content'>
				        <div class='date'>${dayjs(Number(value[0])).format(
					"YYYY.MM.DD"
				)} ~ ${dayjs(Number(value[1])).format("YYYY.MM.DD")}</div>
				        <div class='hiding-duration'>
				            <div class='name'>隐匿时长</div>
				            <div class='time'>234h</div>
				        </div>
				    </div>`;
			},
		},
		data: seriesData,
		xAxisIndex: axisIndex,
		yAxisIndex: axisIndex,
	}
}
// 自定义折线
export const getCustomLineSeries = (seriesData, axisIndex) => {
	return {
		type: "custom",
		clip: true,
		renderItem: function (params, api) {
			const yValue = api.value(3);
			const polylineStyle = {
				stroke: FAULT_COLOR,
				fill: null,
				lineWidth: 2,
			};
			const emphasisStyle = {
				style: {
					lineWidth: 3,
				},
			};
			const x1 = api.coord([api.value(0), 0]);
			const x2 = api.coord([api.value(0), yValue]);
			const x3 = api.coord([api.value(1), yValue]);
			const x4 = api.coord([api.value(1), 0]);
			return {
				type: 'group',
				children: [
					{
						type: "polyline", //折线
						shape: {
							points: [x1, x2, x3, x4]
						},
						style: polylineStyle,
						emphasis: emphasisStyle,
					},
					{
						type: "line", //折线
						shape: {
							x1: x1[0],
							y1: x1[1],
							x2: x4[0],
							y2: x4[1]
						},
						style: {
							stroke: LINE_COLOR,
							fill: null,
							lineWidth: 2
						},
						// emphasis: emphasisStyle,
					}
				]
			}
		},
		encode: {
			x: 0,
			y: 3,
		},
		tooltip: {
			...tooltipConfig,
			formatter: function (params) {
				const { value } = params.data;
				return `<div class='echarts-tooltip-content'>
				        <div class='date'>${dayjs(Number(value[0])).format(
					"YYYY.MM.DD"
				)} ~ ${dayjs(Number(value[1])).format("YYYY.MM.DD")}</div>
				        <div class='hiding-duration'>
				            <div class='name'>故障时长</div>
				            <div class='time'>234h</div>
				        </div>
				        <div class='hiding-duration'>
				            <div class='name'>损失时长</div>
				            <div class='time'>42h</div>
				        </div>
				        <div class='hiding-duration'>
				            <div class='name'>故障感知时长</div>
				            <div class='time'>145h</div>
				        </div>
				    </div>`;
			},
		},
		data: seriesData,
		xAxisIndex: axisIndex,
		yAxisIndex: axisIndex,
	}
}
// 自定义圆圈
export const getCustomCircleSeries = (seriesData, axisIndex) => {
	let pointList = []
	return {
		type: "custom",
		renderItem: function (params, api) {
			let iconLocation = api.value(3);
			let color = api.value(2) ? FAULT_COLOR : NORMAL_COLOR;
			let start = api.coord([api.value(0), api.value(1)]);
			const xValue = start[0];
			const i = pointList.findIndex(
				(x) => x.dataIndex === params.dataIndex
			);
			if (i > -1) {
				pointList[i].x = xValue;
			} else {
				pointList.push({
					dataIndex: params.dataIndex,
					x: xValue,
					hidden: false,
					startTime: api.value(0),
					endTime: null,
				});
			}
			function getPrevShow(index) {
				const prevIndex = index - 1;
				const prevPoint = pointList[prevIndex];
				if (prevPoint?.hidden === false) return prevPoint;
				if (prevIndex > 0) return getPrevShow(prevIndex);
				return null;
			}
			function getPrevHidden(index) {
				const prevIndex = index - 1;
				const prevPoint = pointList[prevIndex];
				if (prevPoint?.hidden) return prevPoint;
				if (prevIndex > 0) return getPrevHidden(prevIndex);
				return null;
			}
			const newIndex = pointList.findIndex(
				(x) => x.dataIndex === params?.dataIndex
			);
			const prevShow = getPrevShow(newIndex);
			let hidden = false;
			if (prevShow) {
				const c = xValue - prevShow.x;
				hidden = c > 0 && c < 12; //直径
			}
			pointList[newIndex].hidden = hidden;
			const prevIndex = pointList.findIndex(
				(x) => x.dataIndex === prevShow?.dataIndex
			);
			if (prevIndex > -1) {
				pointList[prevIndex].endTime = hidden ? api.value(0) : null;
				if (!hidden) {
					const prevHidden = getPrevHidden(newIndex);
					pointList[prevIndex].endTime = prevHidden?.startTime || null;
				}
			}
			if (iconLocation) {
				let imgStyle = api.style({
					image: api.value(2) ? locationIconRed : locationIcon,
					width: 32,
					height: 32,
				});
				const res = {
					z2: 99999,
					type: "image",
					x: start[0] - 15,
					y: start[1] - 30,
					style: imgStyle,
				}
				if ((start[0]) < 50) {
					res.style.width = 0
					res.style.height = 0
				}
				return res;
			}
			const res = {
				type: "circle",
				shape: {
					cx: start[0],
					cy: start[1],
					r: hidden ? 0 : 6,
				},
				style: {
					stroke: color,
					fill: "#FFF",
					lineWidth: hidden ? 0 : 3,
				},
				emphasis: {
					style: {
						lineWidth: 4,
					},
				},
			}
			if (xValue <= 50) res.shape.r = 0
			return res;
		},
		tooltip: {
			show: false,
		},
		data: seriesData,
		xAxisIndex: axisIndex,
		yAxisIndex: axisIndex,
	}
}